package com.example.handheld4_gsignal_app.services;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.example.handheld4_gsignal_app.data.SignalRecord;
import com.example.handheld4_gsignal_app.network.ApiClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

// 移除POI依赖，使用CSV导出

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据导出服务 - 支持Excel、CSV、JSON格式导出
 */
public class DataExportService {
    
    private static final String TAG = "DataExportService";
    private Context context;
    private ApiClient apiClient;
    private Gson gson;
    private SimpleDateFormat dateFormat;
    
    public DataExportService(Context context) {
        this.context = context;
        this.apiClient = new ApiClient();
        this.gson = new Gson();
        this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    }
    
    /**
     * 导出类型枚举
     */
    public enum ExportType {
        EXCEL("excel"),
        CSV("csv"),
        JSON("json");
        
        private final String value;
        
        ExportType(String value) {
            this.value = value;
        }
        
        public String getValue() {
            return value;
        }
    }
    
    /**
     * 导出状态枚举
     */
    public enum ExportStatus {
        PROCESSING("processing"),
        COMPLETED("completed"),
        FAILED("failed");
        
        private final String value;
        
        ExportStatus(String value) {
            this.value = value;
        }
        
        public String getValue() {
            return value;
        }
    }
    
    /**
     * 导出记录模型
     */
    public static class ExportRecord {
        private String exportId;
        private String userId;
        private String teamId;
        private String exportType;
        private String fileName;
        private String filePath;
        private Long fileSize;
        private Map<String, Object> filterCriteria;
        private Integer recordCount;
        private String checksum;
        private String status;
        private String createdAt;
        private String completedAt;
        private String expiresAt;
        
        // Getters and Setters
        public String getExportId() { return exportId; }
        public void setExportId(String exportId) { this.exportId = exportId; }
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        
        public String getTeamId() { return teamId; }
        public void setTeamId(String teamId) { this.teamId = teamId; }
        
        public String getExportType() { return exportType; }
        public void setExportType(String exportType) { this.exportType = exportType; }
        
        public String getFileName() { return fileName; }
        public void setFileName(String fileName) { this.fileName = fileName; }
        
        public String getFilePath() { return filePath; }
        public void setFilePath(String filePath) { this.filePath = filePath; }
        
        public Long getFileSize() { return fileSize; }
        public void setFileSize(Long fileSize) { this.fileSize = fileSize; }
        
        public Map<String, Object> getFilterCriteria() { return filterCriteria; }
        public void setFilterCriteria(Map<String, Object> filterCriteria) { this.filterCriteria = filterCriteria; }
        
        public Integer getRecordCount() { return recordCount; }
        public void setRecordCount(Integer recordCount) { this.recordCount = recordCount; }
        
        public String getChecksum() { return checksum; }
        public void setChecksum(String checksum) { this.checksum = checksum; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
        
        public String getCompletedAt() { return completedAt; }
        public void setCompletedAt(String completedAt) { this.completedAt = completedAt; }
        
        public String getExpiresAt() { return expiresAt; }
        public void setExpiresAt(String expiresAt) { this.expiresAt = expiresAt; }
    }
    
    /**
     * 导出请求模型
     */
    public static class ExportRequest {
        private String exportType;
        private Map<String, Object> filterCriteria;
        private String fileFormat;
        private boolean includeAttachments;
        
        public ExportRequest(ExportType exportType, Map<String, Object> filterCriteria) {
            this.exportType = exportType.getValue();
            this.filterCriteria = filterCriteria != null ? filterCriteria : new HashMap<>();
            this.fileFormat = "xlsx";
            this.includeAttachments = false;
        }
        
        // Getters and Setters
        public String getExportType() { return exportType; }
        public void setExportType(String exportType) { this.exportType = exportType; }
        
        public Map<String, Object> getFilterCriteria() { return filterCriteria; }
        public void setFilterCriteria(Map<String, Object> filterCriteria) { this.filterCriteria = filterCriteria; }
        
        public String getFileFormat() { return fileFormat; }
        public void setFileFormat(String fileFormat) { this.fileFormat = fileFormat; }
        
        public boolean isIncludeAttachments() { return includeAttachments; }
        public void setIncludeAttachments(boolean includeAttachments) { this.includeAttachments = includeAttachments; }
    }
    
    /**
     * 回调接口
     */
    public interface ExportCallback {
        void onSuccess(ExportRecord record);
        void onError(String error);
    }
    
    public interface ExportListCallback {
        void onSuccess(List<ExportRecord> records);
        void onError(String error);
    }
    
    /**
     * 本地导出数据为CSV格式
     */
    public String exportToCSV(List<SignalRecord> records) throws IOException {
        String fileName = "signal_data_" + getCurrentTimestamp() + ".csv";
        File exportFile = createExportFile(fileName);
        
        try (FileWriter writer = new FileWriter(exportFile)) {
            // 写入CSV头部
            writer.append("时间,信号强度(dBm),纬度,经度,网络类型,运营商,基站ID,RSRP,RSRQ,RSSI,SNR\n");
            
            // 写入数据行
            for (SignalRecord record : records) {
                writer.append(String.format(Locale.getDefault(), "%s,%d,%.6f,%.6f,%s,%s,%s,%s,%s,%s,%s\n",
                    record.getCollectedAt(),
                    record.getSignalStrength(),
                    record.getLatitude(),
                    record.getLongitude(),
                    record.getNetworkType() != null ? record.getNetworkType() : "",
                    record.getOperatorName() != null ? record.getOperatorName() : "",
                    record.getCellId() != null ? record.getCellId() : "",
                    record.getRsrp() != 0 ? String.valueOf(record.getRsrp()) : "",
                    record.getRsrq() != 0.0 ? String.valueOf(record.getRsrq()) : "",
                    record.getRssi() != 0 ? String.valueOf(record.getRssi()) : "",
                    record.getSnr() != 0.0 ? String.valueOf(record.getSnr()) : ""
                ));
            }
        }
        
        return exportFile.getAbsolutePath();
    }
    
    /**
     * 本地导出数据为Excel格式（实际为CSV格式）
     */
    public String exportToExcel(List<SignalRecord> records) throws IOException {
        String fileName = "signal_data_" + getCurrentTimestamp() + ".csv";
        File exportFile = createExportFile(fileName);
        
        try (FileWriter writer = new FileWriter(exportFile)) {
            // 写入CSV头部
            writer.append("时间,信号强度(dBm),纬度,经度,网络类型,运营商,基站ID,RSRP,RSRQ,RSSI,SNR\n");
            
            // 写入数据行
            for (SignalRecord record : records) {
                writer.append(String.format(Locale.getDefault(), "%s,%d,%.6f,%.6f,%s,%s,%s,%s,%s,%s,%s\n",
                    record.getCollectedAt(),
                    record.getSignalStrength(),
                    record.getLatitude(),
                    record.getLongitude(),
                    record.getNetworkType() != null ? record.getNetworkType() : "",
                    record.getOperatorName() != null ? record.getOperatorName() : "",
                    record.getCellId() != null ? record.getCellId() : "",
                    record.getRsrp() != 0 ? String.valueOf(record.getRsrp()) : "",
                    record.getRsrq() != 0.0 ? String.valueOf(record.getRsrq()) : "",
                    record.getRssi() != 0 ? String.valueOf(record.getRssi()) : "",
                    record.getSnr() != 0.0 ? String.valueOf(record.getSnr()) : ""
                ));
            }
        }
        
        return exportFile.getAbsolutePath();
    }
    
    /**
     * 本地导出数据为JSON格式
     */
    public String exportToJSON(List<SignalRecord> records) throws IOException {
        String fileName = "signal_data_" + getCurrentTimestamp() + ".json";
        File exportFile = createExportFile(fileName);
        
        // 构建导出数据结构
        Map<String, Object> exportData = new HashMap<>();
        exportData.put("metadata", createExportMetadata(records));
        exportData.put("statistics", generateStatistics(records));
        exportData.put("data", convertRecordsToMap(records));
        
        // 写入JSON文件
        try (FileWriter writer = new FileWriter(exportFile)) {
            gson.toJson(exportData, writer);
        }
        
        return exportFile.getAbsolutePath();
    }
    
    /**
     * 服务器端导出数据
     */
    public void exportDataOnServer(ExportRequest request, ExportCallback callback) {
        try {
            String requestJson = gson.toJson(request);
            Log.d(TAG, "服务器导出请求: " + requestJson);
            
            apiClient.post("/api/v2/exports", requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        ExportRecord record = gson.fromJson(response, ExportRecord.class);
                        Log.d(TAG, "服务器导出成功: " + record.getExportId());
                        callback.onSuccess(record);
                    } catch (Exception e) {
                        Log.e(TAG, "解析服务器导出结果失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "服务器导出失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "服务器导出请求失败", e);
            callback.onError("导出请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取导出历史
     */
    public void getExportHistory(int limit, ExportListCallback callback) {
        try {
            String url = "/api/v2/exports?limit=" + limit;
            Log.d(TAG, "获取导出历史: " + url);
            
            apiClient.get(url, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        Type listType = new TypeToken<List<ExportRecord>>(){}.getType();
                        List<ExportRecord> records = gson.fromJson(response, listType);
                        Log.d(TAG, "获取导出历史成功，数量: " + records.size());
                        callback.onSuccess(records);
                    } catch (Exception e) {
                        Log.e(TAG, "解析导出历史失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "获取导出历史失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "获取导出历史请求失败", e);
            callback.onError("获取请求失败: " + e.getMessage());
        }
    }
    
    // 移除POI相关方法，使用CSV导出
    
    /**
     * 生成统计信息
     */
    private Map<String, Object> generateStatistics(List<SignalRecord> records) {
        Map<String, Object> stats = new HashMap<>();
        
        if (records.isEmpty()) {
            return stats;
        }
        
        // 基本统计
        stats.put("总记录数", records.size());
        
        // 信号强度统计
        List<Integer> signalStrengths = new ArrayList<>();
        for (SignalRecord record : records) {
            signalStrengths.add(record.getSignalStrength());
        }
        
        int sum = 0;
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int strength : signalStrengths) {
            sum += strength;
            min = Math.min(min, strength);
            max = Math.max(max, strength);
        }
        
        stats.put("平均信号强度", String.format("%.2f dBm", (double) sum / signalStrengths.size()));
        stats.put("最强信号", max + " dBm");
        stats.put("最弱信号", min + " dBm");
        stats.put("信号范围", (max - min) + " dBm");
        
        // 时间范围
        if (!records.isEmpty()) {
            String firstTime = records.get(0).getCollectedAt();
            String lastTime = records.get(records.size() - 1).getCollectedAt();
            stats.put("数据时间范围", firstTime + " 至 " + lastTime);
        }
        
        // 设备数量
        Set<String> deviceIds = new HashSet<>();
        for (SignalRecord record : records) {
            deviceIds.add(record.getDeviceId());
        }
        stats.put("设备数量", deviceIds.size());
        
        return stats;
    }
    
    /**
     * 创建导出元数据
     */
    private Map<String, Object> createExportMetadata(List<SignalRecord> records) {
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("导出时间", dateFormat.format(new Date()));
        metadata.put("导出类型", "本地导出");
        metadata.put("记录数量", records.size());
        metadata.put("文件格式", "Excel/CSV/JSON");
        metadata.put("应用版本", "v2.0.0");
        return metadata;
    }
    
    /**
     * 转换记录为Map格式
     */
    private List<Map<String, Object>> convertRecordsToMap(List<SignalRecord> records) {
        List<Map<String, Object>> data = new ArrayList<>();
        for (SignalRecord record : records) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("device_id", record.getDeviceId());
            recordMap.put("signal_strength", record.getSignalStrength());
            recordMap.put("latitude", record.getLatitude());
            recordMap.put("longitude", record.getLongitude());
            recordMap.put("collected_at", record.getCollectedAt());
            recordMap.put("network_type", record.getNetworkType());
            recordMap.put("operator_name", record.getOperatorName());
            recordMap.put("cell_id", record.getCellId());
            recordMap.put("rsrp", record.getRsrp());
            recordMap.put("rsrq", record.getRsrq());
            recordMap.put("rssi", record.getRssi());
            recordMap.put("snr", record.getSnr());
            data.add(recordMap);
        }
        return data;
    }
    
    /**
     * 创建导出文件
     */
    private File createExportFile(String fileName) throws IOException {
        File exportDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "Handheld4GSignal");
        
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        
        File exportFile = new File(exportDir, fileName);
        if (!exportFile.exists()) {
            exportFile.createNewFile();
        }
        
        return exportFile;
    }
    
    /**
     * 获取当前时间戳
     */
    private String getCurrentTimestamp() {
        return new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    }
    
    /**
     * 导出AI分析报告
     */
    public void exportAnalysisReport(List<SignalRecord> records, String analysisType, ExportCallback callback) {
        try {
            Log.d(TAG, "开始导出AI分析报告，记录数: " + records.size() + ", 分析类型: " + analysisType);
            
            // 构建分析报告请求
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("analysis_type", analysisType);
            requestData.put("signal_data", convertRecordsToMap(records));
            requestData.put("export_format", "excel");
            requestData.put("include_analysis", true);
            requestData.put("include_statistics", true);
            requestData.put("include_visualization", true);
            
            String requestJson = gson.toJson(requestData);
            
            // 调用服务器端分析报告导出
            apiClient.post("/api/v2/exports/analysis-report", requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        ExportRecord record = gson.fromJson(response, ExportRecord.class);
                        Log.d(TAG, "AI分析报告导出成功: " + record.getExportId());
                        callback.onSuccess(record);
                    } catch (Exception e) {
                        Log.e(TAG, "解析AI分析报告导出结果失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "AI分析报告导出失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "AI分析报告导出请求失败", e);
            callback.onError("导出请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 本地导出AI分析报告（CSV格式）
     */
    public String exportAnalysisReportLocally(List<SignalRecord> records, String analysisType) throws IOException {
        String fileName = "analysis_report_" + analysisType + "_" + getCurrentTimestamp() + ".csv";
        File exportFile = createExportFile(fileName);
        
        try (FileWriter writer = new FileWriter(exportFile)) {
            // 写入报告标题
            writer.append("4G信号检测系统 - AI分析报告\n");
            writer.append("分析类型: " + analysisType + "\n");
            writer.append("生成时间: " + dateFormat.format(new Date()) + "\n");
            writer.append("数据记录数: " + records.size() + "\n");
            writer.append("分析算法: 信号质量评估\n\n");
            
            // 写入分析摘要
            writer.append("=== 分析摘要 ===\n");
            Map<String, Object> analysisSummary = generateAnalysisSummary(records);
            for (Map.Entry<String, Object> entry : analysisSummary.entrySet()) {
                writer.append(entry.getKey() + ": " + entry.getValue().toString() + "\n");
            }
            writer.append("\n");
            
            // 写入建议措施
            writer.append("=== 建议措施 ===\n");
            List<String> suggestions = generateSuggestions(records);
            for (String suggestion : suggestions) {
                writer.append("• " + suggestion + "\n");
            }
            writer.append("\n");
            
            // 写入AI分析结果数据
            writer.append("=== AI分析结果 ===\n");
            writer.append("时间,信号强度(dBm),AI分析结果,置信度,严重程度,异常类型,建议措施,网络类型,运营商\n");
            
            for (SignalRecord record : records) {
                String aiResult = generateMockAIResult(record.getSignalStrength());
                String confidence = String.format("%.2f", 0.85 + Math.random() * 0.15);
                String severity = getSeverityLevel(record.getSignalStrength());
                String anomalyType = getAnomalyType(record.getSignalStrength());
                String suggestion = getSuggestion(record.getSignalStrength());
                
                writer.append(String.format(Locale.getDefault(), "%s,%d,%s,%s,%s,%s,%s,%s,%s\n",
                    record.getCollectedAt(),
                    record.getSignalStrength(),
                    aiResult,
                    confidence,
                    severity,
                    anomalyType,
                    suggestion,
                    record.getNetworkType() != null ? record.getNetworkType() : "",
                    record.getOperatorName() != null ? record.getOperatorName() : ""
                ));
            }
        }
        
        return exportFile.getAbsolutePath();
    }
    
    // 移除POI相关方法，使用CSV导出
    
    /**
     * 生成模拟AI分析结果
     */
    private String generateMockAIResult(int signalStrength) {
        if (signalStrength >= -70) {
            return "优秀";
        } else if (signalStrength >= -85) {
            return "良好";
        } else if (signalStrength >= -100) {
            return "一般";
        } else {
            return "较差";
        }
    }
    
    /**
     * 获取严重程度级别
     */
    private String getSeverityLevel(int signalStrength) {
        if (signalStrength >= -70) {
            return "低";
        } else if (signalStrength >= -85) {
            return "中";
        } else if (signalStrength >= -100) {
            return "高";
        } else {
            return "严重";
        }
    }
    
    /**
     * 获取异常类型
     */
    private String getAnomalyType(int signalStrength) {
        if (signalStrength >= -85) {
            return "正常";
        } else if (signalStrength >= -100) {
            return "信号衰减";
        } else {
            return "信号中断";
        }
    }
    
    /**
     * 获取建议措施
     */
    private String getSuggestion(int signalStrength) {
        if (signalStrength >= -85) {
            return "信号良好，无需处理";
        } else if (signalStrength >= -100) {
            return "建议检查天线连接或调整位置";
        } else {
            return "建议更换设备或联系技术支持";
        }
    }
    
    /**
     * 生成分析摘要
     */
    private Map<String, Object> generateAnalysisSummary(List<SignalRecord> records) {
        Map<String, Object> summary = new HashMap<>();
        
        if (records.isEmpty()) {
            return summary;
        }
        
        // 统计各等级信号数量
        int excellent = 0, good = 0, fair = 0, poor = 0;
        for (SignalRecord record : records) {
            int strength = record.getSignalStrength();
            if (strength >= -70) excellent++;
            else if (strength >= -85) good++;
            else if (strength >= -100) fair++;
            else poor++;
        }
        
        summary.put("优秀信号数量", excellent);
        summary.put("良好信号数量", good);
        summary.put("一般信号数量", fair);
        summary.put("较差信号数量", poor);
        summary.put("信号质量分布", String.format("优秀:%.1f%%, 良好:%.1f%%, 一般:%.1f%%, 较差:%.1f%%",
            (double) excellent / records.size() * 100,
            (double) good / records.size() * 100,
            (double) fair / records.size() * 100,
            (double) poor / records.size() * 100));
        
        // 平均信号强度
        int totalStrength = 0;
        for (SignalRecord record : records) {
            totalStrength += record.getSignalStrength();
        }
        summary.put("平均信号强度", String.format("%.2f dBm", (double) totalStrength / records.size()));
        
        return summary;
    }
    
    /**
     * 生成建议措施
     */
    private List<String> generateSuggestions(List<SignalRecord> records) {
        List<String> suggestions = new ArrayList<>();
        
        if (records.isEmpty()) {
            return suggestions;
        }
        
        // 分析信号质量分布
        int poorCount = 0;
        for (SignalRecord record : records) {
            if (record.getSignalStrength() < -100) {
                poorCount++;
            }
        }
        
        double poorRatio = (double) poorCount / records.size();
        
        if (poorRatio > 0.3) {
            suggestions.add("信号质量较差，建议检查设备状态和网络环境");
            suggestions.add("考虑更换位置或调整天线方向");
        } else if (poorRatio > 0.1) {
            suggestions.add("部分区域信号较弱，建议优化测试路径");
        } else {
            suggestions.add("信号质量整体良好，建议保持当前测试方案");
        }
        
        suggestions.add("定期检查设备校准状态");
        suggestions.add("关注网络运营商的服务质量变化");
        
        return suggestions;
    }
    
    // 移除POI样式相关方法
    
    /**
     * 获取导出目录路径
     */
    public String getExportDirectory() {
        File exportDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "Handheld4GSignal");
        return exportDir.getAbsolutePath();
    }
}